<template>
  <div class="inner-link">
    <iframe
      ref="iframeRef"
      :src="frameSrc"
      width="100%"
      height="100%"
      frameborder="0"
      @load="handleLoad"
    />
    <div v-if="loading" class="iframe-loading">
      <el-icon class="is-loading" :size="40">
        <Loading />
      </el-icon>
      <p>页面加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { Loading } from '@element-plus/icons-vue'

const route = useRoute()
const iframeRef = ref<HTMLIFrameElement>()
const loading = ref(true)

// 获取iframe源地址
const frameSrc = computed(() => {
  const src = route.query.src as string
  if (!src) return 'about:blank'
  if (!(src.startsWith('http://') || src.startsWith('https://'))) return 'about:blank'
  // 白名单校验（可通过环境变量配置多个域名，逗号分隔）
  const whitelist = (import.meta.env.VITE_IFRAME_WHITELIST || '').split(',').map((s: string) => s.trim()).filter(Boolean)
  try {
    const url = new URL(src)
    if (whitelist.length === 0 || whitelist.includes(url.host) || whitelist.includes(url.origin)) {
      return src
    }
  } catch {
    // ignore
  }
  return 'about:blank'
})

// iframe加载完成
const handleLoad = () => {
  loading.value = false
}

// 监听iframe高度变化
const resizeIframe = () => {
  if (iframeRef.value) {
    try {
      const iframeDoc = iframeRef.value.contentDocument || iframeRef.value.contentWindow?.document
      if (iframeDoc) {
        const height = Math.max(
          iframeDoc.documentElement.scrollHeight,
          iframeDoc.documentElement.offsetHeight,
          iframeDoc.body.scrollHeight,
          iframeDoc.body.offsetHeight
        )
        iframeRef.value.style.height = height + 'px'
      }
    } catch (error) {
      // 跨域时无法访问iframe内容，使用默认高度
      console.warn('Cannot access iframe content due to cross-origin restrictions')
    }
  }
}

let resizeTimer: number

onMounted(() => {
  // 定时调整iframe高度
  resizeTimer = window.setInterval(resizeIframe, 1000)
})

onUnmounted(() => {
  if (resizeTimer) {
    clearInterval(resizeTimer)
  }
})
</script>

<style lang="scss" scoped>
.inner-link {
  position: relative;
  width: 100%;
  height: calc(100vh - 84px);
  
  iframe {
    min-height: 500px;
  }

  .iframe-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    color: var(--el-text-color-secondary);

    .el-icon {
      margin-bottom: 16px;
      color: var(--el-color-primary);
    }

    p {
      margin: 0;
      font-size: 14px;
    }
  }
}
</style>
